<template>
  <a-row style="padding: 10px;">
    <a-col span="24">
      <a-form layout="inline">
        <a-form-item label="角色名称">
          <a-input v-model="search.roleName" placeholder="请输入角色名称！"></a-input>
        </a-form-item>
        <a-form-item label="角色代码">
          <a-input v-model="search.roleCode" placeholder="请输入角色代码！"></a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="searchList">查询</a-button>
        </a-form-item>
      </a-form>
    </a-col>
    <a-col span="24" style="margin: 10px 0">
      <a-button type="primary" @click="addRole">添加角色</a-button>
    </a-col>
    <a-col span="24">
      <a-table :dataSource="data" :columns="columns" :pagination="pagination" :loading="loading" size="small" bordered
               :rowKey="record => record.roleId">
        <template slot="operation" slot-scope="text, record, index">
          <div>
            <span>
              <a @click="() => showMenu(record)">绑定菜单</a>
              <a @click="() => showOrg(record)">授权组织</a>
              <a @click="() => showMember(record)" v-if="record.roleType === 1">授权成员</a>
            </span>
            <span v-if="record.roleSource !== 0">
              <a v-if="record.state == 1 || record.state == 0" @click="() => updateRole(index)">编辑</a>
              <a v-if="record.state == 1" @click="() => lockRole(index)">冻结</a>
              <a v-if="record.state == 1" @click="() => delRole(index)">删除</a>
              <a v-if="record.state == 2" @click="() => lockRole(index)">解冻</a>
            </span>
          </div>
        </template>
      </a-table>
      <NCPagination :page="pageObj" @changePage="(page)=>{this.pageObj = page}" @searchList="searchList"/>
    </a-col>
    <!-- 添加角色 -->
    <a-modal v-model="modal.visible" title="添加角色">
      <a-form :form="modal.form">
        <a-form-item label="角色名称" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol">
          <a-input placeholder="请输入角色名称！"
                   v-decorator="['roleName', {rules: [{ required: true, message: '请输入角色名称！'}]}]"/>
        </a-form-item>
        <a-form-item label="角色代码" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol">
          <a-input placeholder="请输入角色代码！"
                   v-decorator="['roleCode', {rules: [{ required: true, message: '请输入角色代码！'}]}]"/>
        </a-form-item>
        <a-form-item label="角色类型" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol">
          <a-select placeholder="请选择角色类型"
                    v-decorator="['roleType', {rules: [{ required: true, message: '请选择角色类型！'}]}]">
            <a-select-option value="0">组织角色</a-select-option>
            <a-select-option value="1">组织成员角色</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="数据权限" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol">
          <a-select placeholder="请选择数据权限"
                    v-decorator="['dataPower', {rules: [{ required: true, message: '请选择数据权限！'}]}]">
            <a-select-option value="0">可以操作该租户的所有数据</a-select-option>
            <a-select-option value="1">可以操作所属机构及下级机构所有数据</a-select-option>
            <a-select-option value="2">可以操作所属机构及当前机构所有下级机构数据</a-select-option>
            <a-select-option value="3">可以操作所属机构的数据</a-select-option>
            <a-select-option value="4">可以操作当前机构及下级所有机构数据</a-select-option>
            <a-select-option value="5">仅能操作当前机构数据</a-select-option>
            <a-select-option value="6">仅能操作用户自己的数据</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button key="submit" type="primary" :loading="modal.loading" @click="addOrUpdateRoleOk">
          确定
        </a-button>
        <a-button key="back" @click="modal.visible = false">取消</a-button>
      </template>
    </a-modal>
    <!-- 授权信息 -->
    <a-modal v-model="modalPower.visible" :title="modalPower.title">
      <NCTree :tree-all-data="modalPower.allTree" :tree-select-data="modalPower.selectList"
              @onCheck="(data)=> {modalPower.selectList = data}" :checkParent="modalPower.checkParent"/>
      <template slot="footer">
        <a-button key="submit" type="primary" :loading="modal.loading" @click="bindOk">
          确定
        </a-button>
        <a-button key="back" @click="modalPower.visible = false">取消</a-button>
      </template>
    </a-modal>

    <!-- 授权成员信息 -->
    <a-modal v-model="modalMember.visible" title="授权成员信息" width="1200px">
      <a-row style="min-height: 320px;">
        <a-col span="12">
          <div>组织机构信息</div>
          <a-table :dataSource="modalMember.orgList" :columns="modalMember.orgColumns" :pagination="pagination"
                   size="small" bordered :rowKey="record => record.memberId">
            <template slot="operation" slot-scope="text, record, index">
              <span>
                <a @click="() => showMemberPower(record)">查看成员授权</a>
              </span>
            </template>
          </a-table>
        </a-col>
        <a-col span="12">
          <div>授权信息 总人数{{modalMember.allPageObj.total}} 授权{{modalMember.selectMemberList.length}}人</div>
          <a-table :dataSource="modalMember.allMemberList" :columns="modalMember.columns" :pagination="pagination"
                   size="small" bordered :rowKey="record => record.memberId">
            <template slot="operation" slot-scope="text, record, index">
              <span>
                <a @click="() => bindMemberOk(record)" v-if="!record.power">授权</a>
                <a @click="() => unBindMemberOk(record)" v-if="record.power">解除授权</a>
              </span>
            </template>
          </a-table>
          <NCPagination :page="modalMember.allPageObj" @changePage="(page)=>{this.modalMember.allPageObj = page}"
                        @searchList="selectPowerMember"/>
        </a-col>
      </a-row>
      <template slot="footer">
        <a-button key="back" @click="modalMember.visible = false">取消</a-button>
      </template>
    </a-modal>
  </a-row>
</template>

<script>
  import NCTree from '../components/NCTree'
  import NCPagination from '../components/NCPagination'

  export default {
    name: 'Role',
    components: {
      NCTree,
      NCPagination
    },
    data () {
      return {
        pageObj: {total: 10, pageSize: 10, pageNum: 1, pageSizeOptions: ['10', '20', '50', '100']},
        search: {
          roleName: null,
          roleCode: null,
          memberAccount: null,
          memberName: null
        },
        modal: {
          labelCol: {span: 6},
          wrapperCol: {span: 18},
          loading: false,
          title: '添加角色',
          visible: false,
          form: this.$form.createForm(this),
          data: {}
        },
        loading: false,
        data: [],
        selectRole: [],
        pagination: false,
        columns: [
          {
            title: '序号',
            width: '20',
            customRender: (text, record, index) => {
              return index + this.pageObj.pageSize * (this.pageObj.pageNum - 1) + 1
            }
          }, {
            title: '角色名称',
            dataIndex: 'roleName'
          }, {
            title: '角色代码',
            dataIndex: 'roleCode'
          }, {
            title: '角色来源',
            dataIndex: 'roleSource',
            customRender: (text, record, index) => {
              return text === 0 ? '系统预制角色' : '自定义角色'
            }
          }, {
            title: '角色类型',
            dataIndex: 'roleType',
            customRender: (text, record, index) => {
              if (text === 0) {
                return '组织角色'
              }
              if (text === 1) {
                return '组织成员角色'
              }
            }
          }, {
            title: '数据权限',
            dataIndex: 'dataPower',
            customRender: (text, record, index) => {
              if (text === 0) {
                return '可以操作该租户的所有数据'
              }
              if (text === 1) {
                return '可以操作所属机构及下级机构所有数据'
              }
              if (text === 2) {
                return '可以操作所属机构及当前机构所有下级机构数据'
              }
              if (text === 3) {
                return '可以操作所属机构的数据'
              }
              if (text === 4) {
                return '可以操作当前机构及下级所有机构数据'
              }
              if (text === 5) {
                return '仅能操作当前机构数据'
              }
              if (text === 6) {
                return '仅能操作用户自己的数据'
              }
            }
          }, {
            title: '创建时间',
            dataIndex: 'createTime',
            sorter: true
          }, {
            title: '状态',
            dataIndex: 'state',
            sorter: true,
            customRender: (text, record, index) => {
              return text === 2 ? '冻结' : '正常'
            }
          }, {
            title: '操作',
            fixed: 'right',
            width: 300,
            scopedSlots: {customRender: 'operation'}
          }
        ],
        modalPower: {
          visible: false,
          defaultRole: {},
          allTree: [],
          allMenuTree: [],
          allOrgTree: [],
          selectList: [],
          selectKeys: [],
          checkParent: false
        },
        modalMember: {
          pageObj: {total: 0, pageSize: 10, pageNum: 1, pageSizeOptions: ['10', '20', '50', '100']},
          allPageObj: {total: 0, pageSize: 10, pageNum: 1, pageSizeOptions: ['10', '20', '50', '100']},
          visible: false,
          orgList: [],
          selectOrgList: [],
          selectMemberList: [],
          allMemberList: [],
          columns: [
            {title: '成员账号', dataIndex: 'memberAccount'},
            {title: '成员姓名', dataIndex: 'memberName'},
            {title: '手机号', dataIndex: 'telephone'},
            {title: '操作', scopedSlots: {customRender: 'operation'}}
          ],
          orgColumns: [
            {title: '组织机构名称', dataIndex: 'orgName'},
            {title: '组织机构代码', dataIndex: 'orgCode'},
            {title: '操作', scopedSlots: {customRender: 'operation'}}
          ],
          rowSelection: {
            selectedRowKeys: [],
            onChange: (selectedRowKeys, selectedRows) => {
              this.modalMember.rowSelection.selectedRowKeys = selectedRowKeys
            }
          }
        }
      }
    },
    mounted () {
      this.searchList()
      this.selectAllOrg()
      this.selectAllMenu()
    },
    methods: {
      // 查询数据
      searchList () {
        this.loading = true
        this.http.post('upmsApi', '/role/getRoleList', {
          pageNum: this.pageObj.pageNum,
          pageSize: this.pageObj.pageSize,
          data: {
            roleName: this.search.roleName,
            roleCode: this.search.roleCode
          }
        }).then((res) => {
          if (res.success) {
            this.data = res.rows
            this.pageObj.total = res.total
          } else {
            this.$message.error(res.message)
          }
          this.loading = false
        })
      },
      // 添加角色
      addRole () {
        this.modal.visible = true
        this.modal.title = '添加角色'
        this.modal.data = {}
        this.modal.form.setFieldsValue({
          roleName: null,
          roleCode: null
        })
      },
      // 更新角色
      updateRole (index) {
        this.modal.visible = true
        this.modal.title = '编辑角色'
        this.modal.data = this.data[index]
        setTimeout(() => {
          this.modal.form.setFieldsValue({
            roleName: this.modal.data.roleName,
            roleCode: this.modal.data.roleCode
          })
        }, 100)
      },
      // 删除角色
      delRole (index) {
        const that = this
        this.$confirm({
          title: '删除角色！?',
          onOk () {
            return new Promise((resolve, reject) => {
              console.log('删除')
              that.http.post('upmsApi', '/role/delRole', {roleId: that.data[index].roleId}).then((res) => {
                if (res.success) {
                  that.$message.info(res.message)
                  that.searchList()
                  resolve(res.message)
                } else {
                  that.$message.error(res.message)
                  reject(res.message)
                }
              })
            })
          }
        })
      },
      // 锁定/解锁角色
      lockRole (index) {
        console.log('锁定角色' + index)
        const that = this
        this.$confirm({
          title: that.data[index].state === 1 ? '冻结角色！?' : '解冻角色！',
          onOk () {
            return new Promise((resolve, reject) => {
              that.http.post('upmsApi', '/role/lockRole', {
                roleId: that.data[index].roleId,
                state: that.data[index].state === 1 ? 2 : 1
              }).then((res) => {
                if (res.success) {
                  that.$message.info(res.message)
                  that.searchList()
                  resolve(res.message)
                } else {
                  that.$message.error(res.message)
                  reject(res.message)
                }
              })
            })
          }
        })
      },
      // 添加角色
      addOrUpdateRoleOk (e) {
        e.preventDefault()
        this.modal.form.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values)
            this.modal.loading = true
            let url = this.modal.title === '添加角色' ? '/role/addRole' : '/role/updateRole'
            this.http.post('upmsApi', url, {
              roleId: this.modal.data.roleId,
              ...values
            }).then((res) => {
              if (res.success) {
                this.$message.info(res.message)
                this.searchList()
              } else {
                this.$message.error(res.message)
              }
              this.modal.loading = false
              this.modal.visible = false
            })
          }
        })
      },
      // 绑定菜单信息
      showMenu (record) {
        this.modalPower.visible = true
        this.modalPower.checkParent = true
        this.modalPower.title = '绑定菜单信息'
        this.selectRole = record
        this.modalPower.allTree = this.modalPower.allMenuTree
        this.selectBindMenu()
      },
      // 授权组织机构信息
      showOrg (record) {
        this.modalPower.visible = true
        this.modalPower.checkParent = false
        this.modalPower.title = '授权组织机构信息'
        this.selectRole = record
        this.modalPower.allTree = this.modalPower.allOrgTree
        this.selectBindOrg()
      },
      // 授权成员信息
      showMember (record) {
        this.modalMember.visible = true
        this.modalMember.allMemberList = []
        this.modalMember.rowSelection.selectedRowKeys = []
        if (this.selectRole.roleId !== record.roleId) {
          this.selectRole = record
          this.selectBindOrg()
        } else if (this.modalMember.orgList.length === 0) {
          this.selectBindOrg()
        }
      },
      // 查询所有组织机构
      selectAllOrg () {
        this.http.post('upmsApi', '/org/getOrgTree', {}).then((res) => {
          if (res.success) {
            let allOrgTree = res.rows
            this.handleOrgTree(allOrgTree)
            this.modalPower.allOrgTree = allOrgTree
          }
        })
      },
      // 处理组织机构树数据
      handleOrgTree (treeList) {
        treeList.forEach(item => {
          item.title = item.orgName
          item.key = item.orgId
          if (item.children) {
            this.handleOrgTree(item.children)
          }
        })
      },
      // 查询所有菜单
      selectAllMenu () {
        this.http.post('upmsApi', '/menu/getMenuTree', {}).then((res) => {
          if (res.success) {
            let allMenuTree = res.rows
            this.handleMenuTree(allMenuTree)
            this.modalPower.allMenuTree = allMenuTree
          }
        })
      },
      // 处理菜单树数据
      handleMenuTree (treeList) {
        treeList.forEach(item => {
          item.title = item.menuName
          item.key = item.menuId
          if (item.children) {
            this.handleMenuTree(item.children)
          }
        })
      },
      // 查询绑定成功的组织机构
      selectBindOrg () {
        this.http.post('upmsApi', '/role/getOrgListByRoleId', {
          pageSize: -1,
          startNode: {
            roleId: this.selectRole.roleId,
            roleSource: this.selectRole.roleSource
          }
        }).then((res) => {
          if (res.success) {
            let selectData = []
            res.rows.forEach(item => {
              selectData.push(item.orgId)
            })
            this.modalMember.orgList = res.rows
            this.modalPower.selectList = selectData
          }
        })
      },
      // 查询绑定成功的菜单
      selectBindMenu () {
        this.http.post('upmsApi', '/role/getMenuListByRoleId', {
          roleId: this.selectRole.roleId
        }).then((res) => {
          if (res.success) {
            let selectData = []
            res.rows.forEach(item => {
              selectData.push(item.menuId)
            })
            this.modalPower.selectList = selectData
          }
        })
      },
      // 查看授权成员信息
      showMemberPower (record) {
        this.modalMember.selectOrgList = [record.orgId]
        this.selectPowerMember()
      },

      // 查询所有成员
      selectPowerMember () {
        this.http.post('upmsApi', '/member/getMemberList', {
          pageNum: this.modalMember.allPageObj.pageNum,
          pageSize: this.modalMember.allPageObj.pageSize,
          orgList: this.modalMember.selectOrgList,
          data: {
            memberAccount: this.search.memberAccount,
            memberName: this.search.memberName
          }
        }).then((res) => {
          if (res.success) {
            let memberList = res.rows
            this.modalMember.allPageObj.total = res.total
            this.http.post('upmsApi', '/role/getMemberListByRoleId', {
              pageSize: -1,
              pageNum: this.modalMember.pageObj.pageNum,
              orgList: this.modalMember.selectOrgList,
              startNode: {
                roleId: this.selectRole.roleId,
                roleSource: this.selectRole.roleSource
              }
            }).then((res) => {
              if (res.success) {
                this.modalMember.selectMemberList = []
                memberList.forEach(item => {
                  item.power = false
                  res.rows.forEach(item2 => {
                    if (item.memberId === item2.memberId) {
                      item.power = true
                      this.modalMember.selectMemberList.push(item)
                    }
                  })
                })
                this.modalMember.allMemberList = memberList
                console.log(this.modalMember.allMemberList)
              }
            })
          }
        })
      },
      bindOk () {
        let url = ''
        if (this.modalPower.title === '绑定菜单信息') {
          if (this.selectRole.roleSource === 0) {
            this.$message.error('系统角色不允许修改')
            return
          }
          url = '/role/bindRoleMenuByRoleId'
        } else {
          url = '/role/bindRoleOrgByRoleId'
        }
        this.http.post('upmsApi', url, {
          sourceIds: [this.selectRole.roleId],
          targetIds: this.modalPower.selectList
        }).then((res) => {
          if (res.success) {
            this.$message.info(res.message)
            this.modalPower.visible = false
            this.selectRole = {}
          }
        })
      },
      // 绑定
      bindMemberOk (record) {
        this.http.post('upmsApi', '/role/bindRoleMemberByRoleId', {
          sourceIds: [this.selectRole.roleId],
          targetIds: [record.memberId]
        }).then((res) => {
          if (res.success) {
            this.$message.info(res.message)
            this.selectPowerMember()
          }
        })
      },
      // 解绑
      unBindMemberOk (record) {
        this.http.post('upmsApi', '/role/unbindRoleMember', {
          roleId: this.selectRole.roleId,
          memberId: record.memberId
        }).then((res) => {
          if (res.success) {
            this.$message.info(res.message)
            this.selectPowerMember()
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
